﻿#region  文件信息

// ---------------------------------------------------------------------------------------
// <copyright file="WxCommon.cs" company="">
// 作者：李帅伦
// </copyright>
// <summary>
// 类型简介：
// 类型详细：WxCommon.cs
// 创建时间：2014-12-25 12:59
// 修改时间：2014-12-23 17:06
// </summary>
// ---------------------------------------------------------------------------------------
#endregion

using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using WebCommon.Com;

namespace Payment.Weixin2
{
    #region

    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    using WebCommon;

    #endregion

    /// <summary>
    /// The wx common.
    /// </summary>
    public class WxCommon
    {
        #region Public Methods and Operators

        /// <summary>
        /// 获取排序
        /// </summary>
        /// <param name="dictionary">
        /// The dictionary.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetOrderBy(IEnumerable<KeyValuePair<string, string>> dictionary)
        {
            var dy = dictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);

            List<string> strings = new List<string>();
            foreach (var item in dy)
            {
                strings.Add(item.Key + "=" + item.Value);
            }

            string join = string.Join("&", strings);

            return join;
        }

        /// <summary>
        /// The get string sign temp.
        /// </summary>
        /// <param name="str">
        /// The str.
        /// </param>
        /// <param name="paternerKey">
        /// The paterner key.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetStringSignTemp(string str, string paternerKey)
        {
            var md5 = str + "&key=" + paternerKey;
            return Encryption.Md532(md5).ToUpper();
        }

        /// <summary>
        /// The get urlencode.
        /// </summary>
        /// <param name="dictionary">
        /// The dictionary.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetUrlencode(Dictionary<string, string> dictionary)
        {
            var dy = dictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);

            List<string> strings = new List<string>();
            foreach (var item in dy)
            {
                strings.Add(item.Key + "=" + Static.UrlencodeToUpper(item.Value));
            }

            string join = string.Join("&", strings);

            return join;
        }

        /// <summary>
        /// 转成XML
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string ParseXML(Dictionary<string, string> parameters)
        {

            var sb = new StringBuilder();
            sb.Append("<xml>");
            var akeys = new ArrayList(parameters.Keys);
            foreach (string k in akeys)
            {
                var v = (string)parameters[k];
                if (Regex.IsMatch(v, @"^[0-9.]$"))
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }

        /// <summary>
        /// 获取code
        /// </summary>
        /// <param name="wxConfig"></param>
        /// <param name="returl"></param>
        /// <param name="state">订单号</param>
        /// <returns></returns>
        public static string GetCodeUrl(WxConfig wxConfig, string returl,string state)
        {
           returl= System.Web.HttpUtility.UrlEncode(returl);
            return string.Format(
                  "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect", wxConfig.AppId, returl, state);
        }

        /// <summary>
        /// 获取Openid
        /// </summary>
       
        /// <returns></returns>
        public static string GetOpenid(WxConfig wxConfig, string code)
        {
            var data = HttpHelper.PostPage(
                   string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", wxConfig.AppId, wxConfig.Appsecret, code),
                   "");
            if (JObject.Parse(data)["openid"] != null)
            {
                return JObject.Parse(data)["openid"].ToString();
            }
            return "数据错误";
        }
        #endregion
    }
}